package com.imesne.office.excel.read;

import com.imesne.office.excel.model.ExcelCell;
import com.imesne.office.excel.model.ExcelRange;
import com.imesne.office.excel.model.ExcelRow;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.List;

/**
 * Created by liyd on 17/7/3.
 */
public class ExcelRowReaderImpl extends AbstractConfigReader implements ExcelRowReader {

    public boolean isSupportRead(Workbook workbook, Sheet sheet, int sheetIndex, Row row, int rowIndex) {
        List<ExcelRange> ranges = this.getExcelReaderConfig().getExcelRanges();
        //未指定，不限范围
        if (ranges == null || ranges.isEmpty()) {
            return true;
        }
        for (ExcelRange range : ranges) {
            if (range.getSheetNum() - 1 != sheetIndex) {
                continue;
            }
            if (rowIndex >= range.getBeginRowNum() - 1 && rowIndex <= range.getEndRowNum() - 1) {
                return true;
            }
        }
        return false;
    }

    public ExcelRow readExcelRow(Workbook workbook, Sheet sheet, int sheetIndex, Row row, int rowIndex) {

        ExcelRow excelRow = new ExcelRow();
        excelRow.setRowNum(rowIndex + 1);

        if (row == null) {
            return excelRow;
        }
        excelRow.setRow(row);

        ExcelCellReader excelCellReader = this.getExcelReaderConfig().getExcelCellReader();
        int cellCount = row.getLastCellNum();
        for (int i = 0; i < cellCount; i++) {

            Cell cell = row.getCell(i);
            boolean isSupportRead = excelCellReader.isSupportRead(workbook, sheet, sheetIndex, row, rowIndex, cell, i);
            if (!isSupportRead) {
                continue;
            }
            ExcelCell excelCell = excelCellReader.readExcelCell(workbook, sheet, sheetIndex, row, rowIndex, cell, i);

            int mode = AbstractExcelReadProcessor.CONTINUE;

            if (this.getExcelReaderConfig().getExcelReadProcessor() != null) {
                mode = this.getExcelReaderConfig().getExcelReadProcessor().processExcelCell(excelCell, workbook, sheet, sheetIndex, row, rowIndex, cell, i);
            }

            if (mode == AbstractExcelReadProcessor.CONTINUE) {
                excelRow.addCell(excelCell);
            } else if (mode == AbstractExcelReadProcessor.STOP_INCLUSIVE) {
                excelRow.addCell(excelCell);
                break;
            } else if (mode == AbstractExcelReadProcessor.STOP_EXCLUSIVE) {
                break;
            }
        }
        return excelRow;
    }
}
